package com.madi.company.model;

import android.content.res.AssetManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.madi.company.app.GlobalApplication;
import com.madi.company.bean.JobTypeEntity;
import com.madi.company.contract.JobTypeContract;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 丁宁
 * on 2016/12/16.
 */

public class JobTpyeModel implements JobTypeContract.Model {
    @Override
    public Observable<List<JobTypeEntity>> getJobTypeData(final String fileName) {
        return Observable.create(new Observable.OnSubscribe<List<JobTypeEntity>>() {
            @Override
            public void call(Subscriber<? super List<JobTypeEntity>> subscriber) {
                StringBuilder stringBuilder = new StringBuilder();
                try {
                    AssetManager assetManager = GlobalApplication.getAppContext().getAssets();
                    BufferedReader bf = new BufferedReader(new InputStreamReader(
                            assetManager.open(fileName)));
                    String line;
                    while ((line = bf.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String json = stringBuilder.toString();
                if (json!=null){
                    JSONObject data = null;
                    try {
                        data = new JSONObject(json);
                        JSONArray tradeList = data.optJSONArray("jobList");
                        Gson gson = new Gson();
                        List<JobTypeEntity> jobTypeList = gson.fromJson(tradeList.toString(), new TypeToken<List<JobTypeEntity>>() {}.getType());
                        subscriber.onNext(jobTypeList);
                        subscriber.onCompleted();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    @Override
    public Observable<Map<String, Integer>> getSelectedDatas(final Map<String, Integer> map) {
        return Observable.create(new Observable.OnSubscribe<Map<String, Integer>>() {
            @Override
            public void call(Subscriber<? super Map<String, Integer>> subscriber) {
                subscriber.onNext(map);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }
}
